package com.base.myproject.client.HR.Training;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseTreeStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseGridPanel;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.SignleFileUpload;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

/**
 * @author cxghiu410@gmail.com 这个类主要实现“培训手册“的功能，要到一个treeStore和store的数据，
 *         一个grid用来显示数据，利用SignleFileUpload来实现上传的功能
 * @see com.base.myproject.client.ui.SignleFileUpload
 */
public class Training_Manual extends BaseJDBCPanel {

	String treeDepId = null; // 将当前树形结构中选中的部门id保存
	String treeDepName = null; // 将当前树形结构中选中的部门name保存
	TreePanel<TreeNodeModelData> treepanel = null;
	BaseComboBoxForm<BaseModelData> sectionCode = new BaseComboBoxForm<BaseModelData>(
			"id",
			"name",
			"SystemInfo",
			"where name is not null and id is not null and len(id)=(select max(len(id)) from systeminfo)",
			true);

	SignleFileUpload swfu; // 显示上传界面
	List<String> filePath = new ArrayList<String>();
	String bcode = Env.getEnvbcode();

	public Training_Manual() {
		init();
	}

	public void init() {
		initWidget();
		registerMainStore(store);
		registerStore(store);
	}

	public void complete() {
		super.complete();
	}

	public void initWidget() {
		HorizontalPanel hp = new HorizontalPanel();
		hp.setSpacing(2);
		VerticalPanel vp = new VerticalPanel();
		vp.add(this.getGrid());
		hp.add(getTreePanel());
		hp.add(vp);
		add(hp);
		this.layout();
	}

	BaseTreeStore<TreeNodeModelData> treeStore = null;

	private TreePanel<TreeNodeModelData> getTreePanel() {
		if (treepanel == null) {
			initTreePanel();
		}
		return treepanel;
	}

	private BaseTreeStore<TreeNodeModelData> getTreeStore() {
		if (treeStore == null) {
			initTreeStore();
		}
		return treeStore;
	}

	private BaseTreeStore<TreeNodeModelData> initTreeStore() {
		StoreInfo info = new StoreInfo();
		String sql2 = "select icode,id,name from SystemInfo where id is not null order by id asc";
		info.setSql(sql2);
		info.setTreesortcolumn("id");
		info.setKeyname(new String[] { "icode" });
		info.setTablename("SystemInfo");
		treeStore = new BaseTreeStore<TreeNodeModelData>(info, false);
		treeStore.load();
		return treeStore;
	}

	private void initTreePanel() {
		treepanel = new TreePanel<TreeNodeModelData>(getTreeStore());
		Tools.setResize(treepanel, 0.15, 0.98);
		treepanel.setBorders(true);
		treepanel.setDisplayProperty("name");
		treepanel.setCheckStyle(CheckCascade.PARENTS);
		treepanel.setCheckNodes(CheckNodes.BOTH);
		treepanel.getStyle().setLeafIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.tree_file())); 
		treepanel.setCheckable(false);
		treepanel.setAutoLoad(true);
		treepanel.setCaching(true);

		treepanel.addListener(Events.OnClick,
				new Listener<TreePanelEvent<TreeNodeModelData>>() {
					public void handleEvent(TreePanelEvent<TreeNodeModelData> be) {
						if (be.getItem() != null) {
							if (be.getItem().getChildCount() == 0) {
								String id = be.getItem().get("id").toString();
								treeDepId = id;
								treeDepName = be.getItem().get("name")
										.toString();
								set_grid(id);
							}
						}
					}
				});
	}

	private void set_grid(String id) {
		StoreInfo info2 = new StoreInfo();
		info2.setTablename("hr_TrainingManual");
		info2.setKeyname(new String[] { "icode" });
		String where = " where 1=1 and ";
		if (id.length() < 5) {
			where = where + " sectionCode like '" + id + "%25'";
		} else {
			where = where + " sectionCode = '" + id + "'";
		}
		info2.setSql("select * from hr_TrainingManual " + where);// 这里sql的linke
		// %% 有问题
		grid.getBg().getStore().setStoreinfo(info2);
		grid.getBg().getStore().reload();
	}

	BaseStore<BusiObject> store = null;

	private BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}

	private BaseStore<BusiObject> createStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("sectionCode");
		type.getField("sectionCode").setType(String.class);
		type.addField("uploadDate");
		type.getField("uploadDate").setType(Date.class);
		type.addField("uploader");
		type.getField("uploader").setType(String.class);
		type.addField("uploadFile");
		type.getField("uploadFile").setType(String.class);
		type.addField("uploadFileName");
		type.getField("uploadFileName").setType(String.class);

		StoreInfo info = new StoreInfo();
		info.setTablename("hr_TrainingManual");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from hr_TrainingManual");
		store = new BaseStore<BusiObject>(type, info);
		return null;
	}

	ModelType type = new ModelType();

	BaseGridPanel grid = null;

	private BaseGridPanel getGrid() {
		if (grid == null) {
			createGrid();
		}
		return grid;
	}

	/**
	 * 定义一个grid，用来显示手册的数据，并通过实例化一个SignleFileUpload 对象来显示一个上传对话框。
	 * 
	 * @return grid 一个BaseGrid对象
	 */
	private BaseGridPanel createGrid() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C2 = new ColumnConfig("sectionCode", "分部门名称", 120);
		C2.setRenderer(sectionCode);
		columns.add(C2);
		ColumnConfig C5 = new ColumnConfig("uploadFileName", "上传文件", 200);
		C5.setRenderer(new GridCellRenderer<ModelData>() {

			public Object render(ModelData model, String property,
					ColumnData config, int rowIndex, int colIndex,
					ListStore<ModelData> store, Grid<ModelData> grid) {
				return "<b><a style=\"color: #385F95; text-decoration: none;\" href=\""
						+ model.get("uploadFile")
						+ "\" target=\"_blank\">"
						+ model.get("uploadFileName") + "</a>";
			}

		});
		columns.add(C5);
		ColumnConfig C3 = new ColumnConfig("uploadDate", "上传日期", 200);
		C3.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd hh:mm:ss"));
		columns.add(C3);
		ColumnConfig C4 = new ColumnConfig("uploader", "上传人", 120);
		columns.add(C4);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGridPanel(getStore(), cm, true, true) {
			@SuppressWarnings("unchecked")
			public void addnewrecord() {
				if (treeDepId == null) {
					MessageBox.alert("警告", "请选择一个分部门后再添加新信息", null);
					return;
				}
				HashMap hp = new HashMap();
				hp.put("sectionCode", treeDepId);
				hp.put("uploadDate", new Date());
				hp.put("uploader", Env.getEnvname());
				grid.getBg().getStore().add(hp);

				swfu = new SignleFileUpload("*.doc;*.pdf;.docx", 1, 204800);
				swfu.setUrl("gwtbase/uploadFileServlet?table=hr_TrainingManual&file=trainingManual&action=insert");
				swfu.setParent(store);
				swfu.showDialog();
			}

		};
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid.getBg().setSelectionModel(cbs);
		Tools.setResize(grid.getBg(), 0.85, 0.94);
		return grid;
	}

}
